package com.imay.videorecord.utils;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.imay.videorecord.encoder.edit.MediaInfo;
import com.imay.videorecord.encoder.edit.VideoEditor;
import com.imay.videorecord.view.ImayLoadingView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Administrator on 2017/1/3.
 */
public class ImayUtils {

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    public static File getOutputMediaFile(Context context, final int type) {
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) {
                File mediaStorageDir = null;
                if (MEDIA_TYPE_IMAGE == type) {
                    mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES), ImayParams.folderImgName);
                } else if (MEDIA_TYPE_VIDEO == type) {
                    mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_MOVIES), ImayParams.folderVideoName);
                }
                if (mediaStorageDir != null && !mediaStorageDir.exists()) {
                    if (!mediaStorageDir.mkdirs()) {
                        Log.d("MyCameraApp", "failed to create directory");
                        return getFileDirImg(context, type, timeStamp);
                    }
                }
                File mediaFile;
                if (type == MEDIA_TYPE_IMAGE) {
                    mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                            "IMG_" + timeStamp + ".jpg");
                } else if (type == MEDIA_TYPE_VIDEO) {
                    mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                            "VID_" + timeStamp + ".mp4");
                } else {
                    return null;
                }
                try {
                    mediaFile.createNewFile();
                    return mediaFile;
                } catch (Exception e) {
                    return getFileDirImg(context, type, timeStamp);
                }
            } else {
                return getFileDirImg(context, type, timeStamp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SD的file报错之后走的应用内存方法
     * java.io.filenotfoundexception open failed eacces (permission denied)
     *
     * @param context
     * @return
     * @throws IOException
     */
    private static File getFileDirImg(Context context, final int type, String timeStamp) throws IOException {
        String filesDir = context.getApplicationContext().getFilesDir().getAbsolutePath();
        File fileDir = new File(filesDir, ImayParams.folderVideoFile);
        if (!fileDir.exists()) {
            if (!fileDir.mkdirs()) {
                return null;
            }
        }
        if (MEDIA_TYPE_IMAGE == type) {
            File file1 = new File(fileDir.getPath() + File.separator + "IMG_IMAY_" + timeStamp + ".jpg");
            if (file1.exists()) {
                file1.delete();
                file1.createNewFile();
                return file1;
            } else {
                return file1;
            }
        } else if (MEDIA_TYPE_VIDEO == type) {
            File file1 = new File(fileDir.getPath() + File.separator + "MOV_IMAY_" + timeStamp + ".mp4");
            if (file1.exists()) {
                file1.delete();
                file1.createNewFile();
                return file1;
            } else {
                return file1;
            }
        }
        return null;
    }

    /**
     * 获取视频输出路径
     * @return
     */
    public static File getOutputImgFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), ImayParams.folderImgName);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINESE).format(new Date());
        return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    }

    /**
     * 删除视频数据库及对应文件
     * @param context
     * @param path
     * @return
     */
    public static boolean deleteMovFile(Context context, String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists() && file.isFile()) {

                // 删除数据库
                ContentResolver resolver = context.getContentResolver();
                Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=?",
                        new String[] { path }, null);

                if (cursor.moveToFirst()) {
                    long id = cursor.getLong(0);
                    Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    Uri uri = ContentUris.withAppendedId(contentUri, id);
                    resolver.delete(uri, null, null);
                }
                cursor.close();

                // 删除图片
                file.delete();
                return true;
            }
        }
        return false;
    }

    /**
     * 获取视频uri
     * @param context
     * @param path
     * @return
     */
    public static Uri getVideoUri(Context context,String path){
        // 删除数据库
        Uri uri = null;
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = MediaStore.Video.query(resolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI,new String[] { path });
        if (cursor.moveToFirst()) {
            long id = cursor.getLong(0);
            Uri contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            uri = ContentUris.withAppendedId(contentUri, id);
        }
        cursor.close();
        return uri;
    }

    /**
     * 获取视屏缩略图
     * @param filePath
     * @return
     */
    public static Bitmap getVideoThumbnail(Context context,String filePath) {
        if(!TextUtils.isEmpty(filePath)){
            Bitmap bitmap = null;
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(context,Uri.parse(filePath));
                bitmap = retriever.getFrameAtTime();
            }
            catch(IllegalArgumentException e) {
                e.printStackTrace();
            }
            catch (RuntimeException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    retriever.release();
                }
                catch (RuntimeException e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }
        return null;
    }

    /**
     * 释放图片资源
     * @param bitmap
     */
    public static void recycledBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    /**
     * 创建loading框
     * @param ctx
     * @param msg
     * @return
     */
    public static Dialog createDialog(Context ctx, String msg) {
        ImayLoadingView dialog = new ImayLoadingView(ctx);
        dialog.setTitle(msg);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    /**
     * 短视频截图
     * @param context
     * @param bitmap
     * @return
     */
    public static String bitmapToLocal(Context context,Bitmap bitmap){
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File file = getFileDirImg(context,MEDIA_TYPE_IMAGE,timeStamp);
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            //保存图片后发送广播通知更新数据库
            //Uri uri = Uri.fromFile(file);
            //context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 视频拼接 采用ffmpeg
     * @param editor
     * @param srcVideo
     * @param srcVideo2
     * @param dstVideo
     * @return
     */
    public static int demoVideoConcat(VideoEditor editor, String srcVideo,String srcVideo2, String dstVideo)
    {
        MediaInfo info1 = new MediaInfo(srcVideo);
        MediaInfo info2 = new MediaInfo(srcVideo2);
        int ret=-1;

        //第一步:先创建三个视频文件,并剪切好视频.
        String seg1=SDKFileUtils.createFileInBox(info1.fileSuffix);
        //String seg2=SDKFileUtils.createFileInBox(info2.fileSuffix);

        String segTs1=SDKFileUtils.createFileInBox("ts");
        String segTs2=SDKFileUtils.createFileInBox("ts");

        //ret=editor.executeVideoCutOut(srcVideo2,seg2, 0,info2.vDuration);


        //第二步: 把他们转换为ts格式.
        //ret=editor.executeConvertMp4toTs(info2.filePath, segTs2);

        //第三步: 把ts文件拼接成mp4
        //ret=editor.executeConvertTsToMp4(new String[]{segTs1,segTs2} , dstVideo);

        //第四步: 删除之前的临时文件.

        SDKFileUtils.deleteFile(segTs2);
        SDKFileUtils.deleteFile(segTs1);
        //SDKFileUtils.deleteFile(seg2);
        //SDKFileUtils.deleteFile(seg1);

        return ret;
    }
}
